//
//  WmcAlbumProjectsVM.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/3/23.
//

import Photos
import RxRelay
import UIKit

class WmcSystemAlbumVM: WmcBaseVM {
    /// 相册列表信号
    let albumListRelay: BehaviorRelay<[WmcAlbumManager.AlbumModel]> = .init(value: [])
    
    /// 显示的相册
    let currentAlbumRelay: BehaviorRelay<WmcAlbumManager.AlbumModel?> = .init(value: nil)
    /// 相册图片的数据
    let albumPhotosRelay: BehaviorRelay<[PHAsset]> = .init(value: [])

    /// 请求相册列表
    func loadAlbumList() {
        let list = WmcAlbumManager.getAllAlbum()
        albumListRelay.accept(list)
    }

    /// 选中一个相册
    func selectAlbum(_ album: WmcAlbumManager.AlbumModel) {
        // 设置匹配选中相册
        var selectAlbum = album
        for _album in albumListRelay.value {
            if _album.hash == album.hash {
                selectAlbum = _album
                break
            }
        }
        currentAlbumRelay.accept(selectAlbum)
        // 倒叙排列相册内图片
        var assetList: [PHAsset] = []
        for i in (0 ..< selectAlbum.count).reversed() {
            let asset = selectAlbum.result.object(at: i)
            assetList.append(asset)
        }
        if !assetList.isEmpty { // 非空判断
            albumPhotosRelay.accept(assetList)
        }
    }
}
